package fr.upmc.aladyn.transactionables.saveobject;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import fr.upmc.aladyn.transactionables.saveobject.SaveRestoreObject;
import fr.upmc.aladyn.transactionables.tests.objects.Point3D;


/**
 * <p>Test class</p>
 * @author Alexis Deluze
 *
 */
public class TestManuelAppelSuccessifFiniParException {
	private Point3D point3d;
	private SaveRestoreObject sro;
	private SaveRestoreObject sro2;
	private int xini;
	private int yini;
	private int zini;
	private int xini2;
	private int yini2;
	private int zini2;
	
	@Before
	public void initialise(){
		System.out.println("Debut du Test TestAppelSuccessifFiniParException");
		
		point3d = new Point3D(0, 0, 0);
		
		xini = point3d.getX();
		yini = point3d.getY();
		zini = point3d.getZ();
		
		sro = new SaveRestoreObject(point3d);
		sro2 = new SaveRestoreObject(point3d);
	}

	
	@After
	public void end(){
		System.out.println("Fin du Test TestAppelSuccessifFiniParException");
	}
	
	@Test
	public void test() {
		
		try {
			 
			sro.save();
			
			point3d.setX(2);
			point3d.setZ(9);
			
			methode(false);
			methode(true);
			
			point3d.setY(3);
			
		} catch (Exception e) {
			sro.restore();
		}
		
		assertTrue(zini == point3d.getZ());
		assertTrue(xini == point3d.getX());
		assertTrue(yini == point3d.getY());
	}
	
	
	public void methodWithException() throws Exception{
		System.out.println("Lancement d'une exception.");
		throw new Exception("Lancement d'une exception.");
	}

	public void methode(boolean willFail) throws Exception{
		
		xini2 = point3d.getX();
		yini2 = point3d.getY();
		zini2 = point3d.getZ();
		
		try {
			
			point3d.setX(5);
			point3d.setY(9);
			point3d.setZ(7);
			
			if(willFail){
				methodWithException();
			}
			
		} catch (Exception e) {
			sro2.restore();
			
			assertTrue(zini2 == point3d.getZ());
			assertTrue(xini2 == point3d.getX());
			assertTrue(yini2 == point3d.getY());
			
			throw e;
		}
	}
}
